package zqservlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(name = "picServlet", urlPatterns = "/dopic")
public class picServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        downloadImageAjax(request,response);
    }

    private static final int BUFFER_SIZE = 32768 * 8;
    private static void downloadImageAjax(HttpServletRequest request, HttpServletResponse response)throws IOException
    {
        File docStorePath = getDocStoreDir(request);
        String pictureName = request.getParameter("pictureName");
        File file = new File(docStorePath+ File.separator+pictureName);
        FileInputStream fis = new FileInputStream(file);
        response.setHeader("Cache-Control", "pre-check=0, post-check=0, max-age=0");
        String fileNameKey = "filename";
        response.addHeader("Content-Disposition", "picture; "+fileNameKey+"=\"" + pictureName + "\"");
        OutputStream os = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            int read;
            while ((read = fis.read(buffer)) != -1) {
                os.write(buffer, 0, read);
            }
        } finally {
            fis.close();
        }
    }

    private static File getDocStoreDir(HttpServletRequest request)
    {
        String docStorePath = null;
        File docStoreDir =null;
        ServletContext context = request.getSession().getServletContext();
        String path = context.getRealPath("/");
        docStorePath =  path + "../w-hkwtzximage";
        File file = new File(docStorePath);
        if(!file.exists()){
            file.mkdirs();
        }
        docStoreDir = file;
        return docStoreDir;
    }
}
